#!/usr/bin/env python3

import os
import json
import re
from urllib import request


OWNER="enmotech"
URL=f"https://gitee.com/api/v5/repos/{OWNER}/issues"
REPO="mogdb-docs"
TITLE="Docs Link Issue"
FILE="lychee_out.md"


def main():
    ACCESS_TOKEN = ""
    if "ACCESS_TOKEN" in os.environ:
        ACCESS_TOKEN=os.environ["ACCESS_TOKEN"]

    if ACCESS_TOKEN == "":
        print("ACCESS_TOKEN IS NULL")
        return

    f = open(FILE, encoding="utf-8")
    BODY=f.read()
    f.close()

    if BODY.find("Errors per input") <0:
        print("Not Found Errors")
        return

    url=URL.format(OWNER=OWNER)
    req = request.Request(url, method="POST")
    req.add_header("Content-Type", "application/json;charset=UTF-8")
    data = {
        "access_token": ACCESS_TOKEN,
        "repo": REPO,
        "title": TITLE,
        "body": BODY
    }
    bs = json.dumps(data).encode('utf-8')
    req.add_header('Content-Length', len(bs))
    resp = request.urlopen(req, bs)
    print("response id:", json.loads(resp.read().decode("utf-8"))["id"])


if __name__ == "__main__":
    if os.path.exists(FILE):
        main()
    else:
        print("file " + FILE + " no exited")
